package com.takepoints21.mobile;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableRow;
import android.widget.TextView;

import com.takepoints.android.TPConst;
import com.takepoints.android.bo.CustomerSiteInfo;
import com.takepoints.android.bo.Promotion;
import com.takepoints.android.services.PublicServices;
import com.takepoints.android.util.AnimationUtil;
import com.takepoints.android.util.DownloadImageTask;
import com.takepoints.android.util.StringUtil;
import com.takepoints.android.vo.TakeReturn;

public class TPPromotions extends BaseActivity {
	
	private TextView txtHeader = null;
	private ImageView imgCurrLoc = null;
	
	private ListView lstItems = null;
	private PromoListAdapter promoAdapter = null;
	private String nfcId = null;
	
	private final String IMG_URL = "https://www.takepoints.com/public/uploads/tmobile/";
	
	public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.items);
        
        Bundle bundle = getIntent().getExtras();
        nfcId = bundle.getString("nfcId");
    	
        txtHeader = (TextView)findViewById(R.id.txtHeader);
        txtHeader.setText("กรุณาเลือกโปรโมชั่น ..");
        
        imgCurrLoc = (ImageView)findViewById(R.id.imgCurrLoc);
        
        manageMenu(0);
        
        lstItems = (ListView)findViewById(R.id.lstItems);
        lstItems.setLayoutAnimation(new AnimationUtil().getSlideDownAnimateCtrl());
        
        promoAdapter = new PromoListAdapter(new ArrayList<Promotion>());
        lstItems.setAdapter(promoAdapter);
        
        if(!StringUtil.isEmpty(nfcId)){
        	new SiteInfoProcess().execute();
        	new FetchPromotions(this).execute();
        }
	}
	
	private class PromoListAdapter extends BaseAdapter {
		private List<Promotion> promotions;
		private LayoutInflater mInflater;

		public PromoListAdapter(List<Promotion> promotions){
			mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			this.promotions = promotions;
		}
		
		public void add(Promotion promotion){
			promotions.add(promotion);
			notifyDataSetChanged();
		}
		
		public void removeAll(){
			promotions.clear();
			notifyDataSetChanged();
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent){
			final Promotion promotion = promotions.get(position);
			if(promotion != null){
				if("1".equals(promotion.getPromoTypeId())){
					convertView = mInflater.inflate(R.layout.mycardrow, null);
				} else if("2".equals(promotion.getPromoTypeId())){
					convertView = mInflater.inflate(R.layout.mycouponrow, null);
				} else if("3".equals(promotion.getPromoTypeId())){
					convertView = mInflater.inflate(R.layout.myrewardrow, null);
				} else{
					convertView = mInflater.inflate(R.layout.myitemrow, null);
				}
				
				final TableRow tblCard = (TableRow)convertView.findViewById(R.id.tblCard);
				
				ImageView imgCard = (ImageView)convertView.findViewById(R.id.imgCard);
				if(imgCard != null){
					Bitmap bitmap = BitmapFactory.decodeFile(IMG_CACHE_PATH + promotion.getPicture());
					if(bitmap != null){
						imgCard.setImageBitmap(bitmap);
					} else{
						imgCard.setTag(IMG_URL + promotion.getPicture());
						new DownloadImageTask().execute(imgCard);
					}
				}
				
				LinearLayout lnrDetail = (LinearLayout)convertView.findViewById(R.id.lnrDetail);
				lnrDetail.removeAllViews();
				if(lnrDetail != null){
					TextView txtTitle = new TextView(lnrDetail.getContext());
					txtTitle.setText(promotion.getCustomerName());
					txtTitle.setTextSize(12);
					txtTitle.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
					txtTitle.setTextColor(Color.parseColor("#78a023"));
					txtTitle.setHeight(LayoutParams.WRAP_CONTENT);
					txtTitle.setPadding(10, 1, 1, 1);
					txtTitle.setSingleLine(false);
					lnrDetail.addView(txtTitle);
					
					TextView txt1 = new TextView(lnrDetail.getContext());
					txt1.setText(promotion.getTitleName());
					txt1.setTextSize(11);
					txt1.setTextColor(Color.parseColor("#404a4a"));
        	        txt1.setHeight(LayoutParams.WRAP_CONTENT);
					txt1.setPadding(9, 1, 1, 1);
					txt1.setSingleLine(false);
					lnrDetail.addView(txt1);
					
					TextView txtPointGet = new TextView(lnrDetail.getContext());
					txtPointGet.setText( "ได้  " + promotion.getOfferPts() + " แต้ม"
									   + "  ( ภายในวันที่  " + promotion.getExpiryDate() + " )");
					txtPointGet.setTextSize(9);
					txtPointGet.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
					txtPointGet.setTextColor(Color.parseColor("#f7941d"));
					txtPointGet.setPadding(10, 3, 1, 1);
					lnrDetail.addView(txtPointGet);
				}
				
				convertView.setOnClickListener(new View.OnClickListener(){
					 public void onClick(View view) {
						 new TakeNowProcess(view.getContext()).execute(promotion.getPromotionId()
								 									  , nfcId);
					 }
				});
				convertView.setOnTouchListener(new View.OnTouchListener(){
					 public boolean onTouch(View v, MotionEvent event){
						 int action = event.getAction();
						 switch(action){
						 	case MotionEvent.ACTION_DOWN:
						 		tblCard.setBackgroundColor(Color.LTGRAY);
						 		break;
						 	case MotionEvent.ACTION_UP:
						 		tblCard.setBackgroundResource(R.drawable.bglist);
						 		break;
						 	case MotionEvent.ACTION_MOVE:
						 		tblCard.setBackgroundResource(R.drawable.bglist);
						 		break;
						 	case MotionEvent.ACTION_CANCEL:
						 		tblCard.setBackgroundResource(R.drawable.bglist);
						 		break;
						 	default:
						 		break;
						 }
						 return false;
					}
				 });
			} else{
				if(convertView == null){
					convertView = mInflater.inflate(R.layout.myitemrow, null);
				}
			}
			return convertView;
		}

		@Override
		public int getCount() {
			return promotions.size();
		}

		@Override
		public Object getItem(int position) {
			return promotions.get(position);
		}

		@Override
		public long getItemId(int position) {
			return promotions.get(position).hashCode();
		}
	}
	
	@Override
	public void onBackPressed(){
		Intent homeInt = new Intent(this, Takepoints.class);
		startActivityForResult(homeInt, 0);
		return;
	}
	
	class SiteInfoProcess extends AsyncTask<Void, Void, CustomerSiteInfo>{
		
		@Override
        protected void onPreExecute(){
            super.onPreExecute();
		}
		
		@Override
        protected CustomerSiteInfo doInBackground(Void... params){
			return PublicServices.getSiteInfoByNfcId(nfcId);
		}
		
		@Override
        protected void onPostExecute(final CustomerSiteInfo siteInfo){
        	if(siteInfo != null){
		        txtHeader.setText("กรุณาเลือกโปรโมชั่น .. " + siteInfo.getSiteName());
		        
		        imgCurrLoc = (ImageView)findViewById(R.id.imgCurrLoc);
		        imgCurrLoc.setOnClickListener(new View.OnClickListener(){
					 public void onClick(View view) {
						 Intent nearByInt = new Intent(view.getContext(), NearBy.class);
						 nearByInt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
						 if(!StringUtil.isEmpty(siteInfo.getLatitude())
								 && !StringUtil.isEmpty(siteInfo.getLongtitude())){
							 nearByInt.putExtra(TPConst.LOCATE_TYPE, TPConst.LOCATE_TYPE_SPECIFIC);
							 nearByInt.putExtra("latParam", siteInfo.getLatitude());
							 nearByInt.putExtra("longParam", siteInfo.getLongtitude());
							 nearByInt.putExtra("siteName", siteInfo.getSiteName());
						 } else{
							 nearByInt.putExtra(TPConst.LOCATE_TYPE, TPConst.LOCATE_TYPE_NEAR_BY);
						 }
						 startActivity(nearByInt);
					 }
				});
			}
		}
		
	}
	
	class FetchPromotions extends AsyncTask<Void, Void, List<Promotion>>{
    	
		private Context context = null;
		private ProgressDialog progressDlg = null;
		
		FetchPromotions(Context context){
			this.context = context;
		}
		
        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            progressDlg = ProgressDialog.show(context, "Takepoints.com", "กำลังโหลดโปรโมชั่น ...", true);
        }
        
        @Override
        protected List<Promotion> doInBackground(Void... params){
        	List<Promotion> promoL = PublicServices.getSitePromoListByNfcId(nfcId);
        	return promoL;
        }
        
        @Override
        protected void onPostExecute(List<Promotion> result){
        	int rows = (result==null)?0:result.size();
        	if(rows > 0){
	    		try{
	    			for(int i=0; i<rows; i++){
	    				promoAdapter.add(result.get(i));
	    			}
	    		} catch(Exception e){
	    			alert("ผิดพลาด : " + e.getMessage());
	    		}
        	}
        	progressDlg.dismiss();
        	popup("มีทั้งหมด " + rows + " รายการ");
        }
    }
	
	class TakeNowProcess extends AsyncTask<String, Void, TakeReturn>{
		
		private Context context = null;
		private ProgressDialog progressDlg = null;
		
		TakeNowProcess(Context context){
			this.context = context;
		}
		
		@Override
        protected void onPreExecute(){
            super.onPreExecute();
            progressDlg = ProgressDialog.show(context, "Takepoints.com", "Taking ...", true);
		}
		
		@Override
        protected TakeReturn doInBackground(String... params){
			String promotionId = params[0];
			TakeReturn tr = new TakeReturn();
			try{
				tr = PublicServices.takeNow( getSharedIntValue(TPConst.PRF_MEMBER_ID)
										   , promotionId
										   , nfcId );
			} catch(Exception e){
				tr.setMessage(e.getMessage());
			}
			return tr;
		}
		
		@Override
        protected void onPostExecute(TakeReturn tr){
        	progressDlg.dismiss();
        	if(tr != null && !StringUtil.isEmpty(tr.getTrxCode())){
        		alertResult( "กรุณาแสดงรหัสนี้แก่พนักงาน : " + tr.getTrxCode()
        				 + (!StringUtil.isEmpty(tr.getTrxDesc())?"\n\n(" + tr.getTrxDesc() + ")":"") );
        		
			} else if(tr != null && !StringUtil.isEmpty(tr.getMessage())){
				alertResult(tr.getMessage());
				
			} else{
				alertResult("พบข้อผิดพลาด !\n\nไม่สามารถ TAKE ได้ ...");
			}
		}
		
	}
	
	private void alertResult(String msg){
		final AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
		alertbox.setMessage(msg);
		alertbox.setPositiveButton("OK", new DialogInterface.OnClickListener(){
			public void onClick(DialogInterface dlgInf, int which){
				backToHome();
			}
		});
		alertbox.show();
	}
	private void backToHome(){
		Intent intent = new Intent(this, Takepoints.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
    }
	
}
